package com.i2863.shiroDemo.util;


import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author cexy
 * @date 2021/5/17 10:33
 * @description
 **/
@Slf4j
public class HttpSessionUtils {
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";

    public static CloseableHttpClient buildHttpClient() {
        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setConnectTimeout(50000)
                .setSocketTimeout(50000).build();
        PoolingHttpClientConnectionManager conMgr = new PoolingHttpClientConnectionManager();
        conMgr.setDefaultMaxPerRoute(20);
        conMgr.setMaxTotal(100);
        CookieStore cookieStore = new BasicCookieStore();
        return HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(conMgr).setDefaultCookieStore(cookieStore).build();
    }

    public static CloseableHttpClient buildHttpClient(CookieStore cookieStore) {
        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setConnectTimeout(50000)
                .setSocketTimeout(50000).build();
        PoolingHttpClientConnectionManager conMgr = new PoolingHttpClientConnectionManager();
        conMgr.setDefaultMaxPerRoute(20);
        conMgr.setMaxTotal(100);
        return HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(conMgr).setDefaultCookieStore(cookieStore).build();
    }

    public static UrlEncodedFormEntity httpPostParameters(Map<String, String> map, Charset charset) {
        List<BasicNameValuePair> params = new ArrayList<>();
        Set<String> keys = map.keySet();
        for (String name : keys) {
            String value = map.get(name);
            BasicNameValuePair nameValuePair = new BasicNameValuePair(name, value);
            params.add(nameValuePair);
        }
        return new UrlEncodedFormEntity(params, charset == null ? StandardCharsets.UTF_8 : charset);
    }

    public static String httpGetUrl(String url, Map<String, String> map) {
        List<BasicNameValuePair> params = new ArrayList<>();
        Set<String> keys = map.keySet();
        for (String name : keys) {
            Object value = map.get(name);
            BasicNameValuePair nameValuePair = new BasicNameValuePair(name, value.toString());
            params.add(nameValuePair);
        }
        String queryString = URLEncodedUtils.format(params, StandardCharsets.UTF_8);
        return url + "?" + queryString;
    }

    public static String httpPost(HttpClient httpClient, String url, Map<String, String> map) throws IOException {
        return httpPost(httpClient, url, map, "utf-8");
    }

    public static String httpPost(HttpClient httpClient, String url, Map<String, String> map, String charset) throws IOException {
        String result;
        HttpPost post = new HttpPost(url);
        post.setEntity(httpPostParameters(map, StandardCharsets.UTF_8));
        post.setHeader(HTTP.USER_AGENT, USER_AGENT);
        HttpResponse response = httpClient.execute(post);
        result = EntityUtils.toString(response.getEntity(), charset);
        return result;
    }

    public static String httpPost(HttpClient httpClient, String url, JsonObject json, String charset) throws IOException {
        String result;
        HttpPost post = new HttpPost(url);
        StringEntity se = new StringEntity(json.toString(), "utf-8");
        post.setEntity(se);
        post.setHeader(HTTP.USER_AGENT, USER_AGENT);
        post.setHeader(HTTP.CONTENT_TYPE, "application/json");
        HttpResponse response = httpClient.execute(post);
        result = EntityUtils.toString(response.getEntity(), charset);
        return result;
    }

    public static String httpPost(HttpClient httpClient, String url, String str, String charset) throws IOException {
        String result;
        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity(str, charset));
        post.setHeader(HTTP.USER_AGENT, USER_AGENT);
        HttpResponse response = httpClient.execute(post);
        result = EntityUtils.toString(response.getEntity(), charset);
        return result;
    }

    public static String httpPost(HttpClient httpClient, String url, String charset) throws IOException {
        String result;
        HttpPost post = new HttpPost(url);
        post.setHeader(HTTP.USER_AGENT, USER_AGENT);
        HttpResponse response = httpClient.execute(post);
        result = EntityUtils.toString(response.getEntity(), charset);
        return result;
    }

    public static String httpPost(HttpClient httpClient, String url, Map<String, String> map, Charset paramEncoding, Charset charset) throws IOException {
        String result;
        HttpPost post = new HttpPost(url);
        post.setEntity(httpPostParameters(map, paramEncoding));
        post.setHeader(HTTP.USER_AGENT, USER_AGENT);
        HttpResponse response = httpClient.execute(post);
        result = EntityUtils.toString(response.getEntity(), charset);
        return result;
    }

    public static HttpResponse httpPostHeaders(HttpClient httpClient, String url, Map<String, String> map) {
        int codeStatus = 500;
        HttpResponse response = null;
        try {
            HttpPost post = new HttpPost(url);
            post.setEntity(httpPostParameters(map, StandardCharsets.UTF_8));
            post.setHeader(HTTP.USER_AGENT, USER_AGENT);
            response = httpClient.execute(post);
            codeStatus = response.getStatusLine().getStatusCode();
        } catch (IOException e) {
            e.printStackTrace();
            log.info("请求URL失败:" + url + "  code:" + codeStatus);
        }
        return response;
    }

    public static String httpGet(CloseableHttpClient httpClient, String url, Map<String, String> map, Charset charset) {
        int codeStatus = 500;
        String result = "";
        try {
            String urls = httpGetUrl(url, map);
            HttpGet get = new HttpGet(urls);
            get.setHeader(HTTP.USER_AGENT, USER_AGENT);
            CloseableHttpResponse response = httpClient.execute(get);
            codeStatus = response.getStatusLine().getStatusCode();
            result = EntityUtils.toString(response.getEntity(), charset);
        } catch (IOException e) {
            log.info("请求URL失败:" + url + "  code:" + codeStatus);
        }
        return result;
    }

    public static String httpGet(CloseableHttpClient httpClient, String url, Map<String, String> map) {
        return httpGet(httpClient, url, map, StandardCharsets.UTF_8);
    }

    public static String httpGet(String url) {
        return httpGet(buildHttpClient(), url, StandardCharsets.UTF_8);
    }

    public static String httpGet(HttpClient httpClient, String url) {
        return httpGet(httpClient, url, StandardCharsets.UTF_8);
    }

    public static String httpGet(HttpClient httpClient, String url, Charset charset) {
        int codeStatus = 500;
        String result = "";
        try {
            HttpGet get = new HttpGet(url);
            get.setHeader(HTTP.USER_AGENT, USER_AGENT);
            HttpResponse response = httpClient.execute(get);
            codeStatus = response.getStatusLine().getStatusCode();
            result = EntityUtils.toString(response.getEntity(), charset);
        } catch (IOException e) {
            log.info("请求URL失败:" + url + "  code:" + codeStatus);
        }
        return result;
    }

    public static InputStream httpContent(CloseableHttpClient httpClient, String url) {
        int codeStatus = 500;
        InputStream inputStream = null;
        try {
            HttpGet get = new HttpGet(url);
            get.setHeader(HTTP.USER_AGENT, USER_AGENT);
            CloseableHttpResponse response = httpClient.execute(get);
            codeStatus = response.getStatusLine().getStatusCode();
            inputStream = response.getEntity().getContent();
        } catch (IOException e) {
            log.info("请求URL失败:" + url + "  code:" + codeStatus);
        }
        return inputStream;
    }

    public static byte[] httpGetByte(CloseableHttpClient httpClient, String url) {
        int codeStatus = 0;
        byte[] bytes;
        try {
            HttpGet get = new HttpGet(url);
            get.setHeader(HTTP.USER_AGENT, USER_AGENT);
            CloseableHttpResponse response = httpClient.execute(get);
            codeStatus = response.getStatusLine().getStatusCode();
            bytes = EntityUtils.toByteArray(response.getEntity());
        } catch (IOException e) {
            log.info("请求URL失败:" + url + "  code:" + codeStatus);
            throw new RuntimeException(e);
        }
        return bytes;
    }

/*    public static void main(String[] args) throws IOException {
        System.out.println(httpGet(buildHttpClient(),"https://www.lagou.com/jobs/3312624.html"));
    }*/
}
